<script setup>
import { mainStore } from '../../../store/mainStore'
import { Delete } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import confirmDialog from '/src/components/ConfirmDialog.vue'
import { _getFileList, _deleteFile, _buildPack } from '/src/api/FileTransfer/main.js'
import zhCn from 'element-plus/es/locale/lang/zh-cn'

let showDeleteDialog = ref(false)
let showBuilderDialog = ref(false)
let showDownloadDialog = ref(false)

const store = mainStore()

const showTableData = ref([]) //  用以展示表格数据的数组
let oriTableData = [] // 请求的原始数据
let copyTableData = [] // 备份的数组 查询要用
let total = ref(0)
const getAllList = async () => {
  try {
    const res = await _getFileList()

    console.log(res)

    if (res?.data?.code == 200) {
      total.value = res.data.data['upload-list'].length
      oriTableData = res.data.data['upload-list']
      copyTableData = res.data.data['upload-list']
    }
  } catch (error) {
    console.error(error)
  }
}

// 打开删除确认框 拿到要删除的元素
let deleteInfo = ref({})
const openDiglog = (params) => {
  deleteInfo.value = params
  deleteInfo.value.title = '文件删除提示'
  deleteInfo.value.content = {
    title: `是否删除文件: `,
    text: `${params['file-name']}`,
  }

  showDeleteDialog.value = true
}

// 根据名字和时间查询数据
let inputName = ref('')
let dateTime = ref()
const searchByNameDate = () => {
  oriTableData = JSON.parse(JSON.stringify(copyTableData))
  // 先对名称进行过滤
  const arr = oriTableData.filter((item) => item['file-name'].includes(inputName.value))
  // 再对时间进行过滤
  if (dateTime.value) {
    const strtTime = new Date(dateTime.value[0])
    const endTime = new Date(dateTime.value[1])

    oriTableData = arr.filter((item) => {
      const itemDate = new Date(item['last-modified'])
      if (itemDate > strtTime && itemDate <= endTime) {
        return item
      }
    })
  } else {
    oriTableData = arr
  }

  toPageData(1)
  total.value = oriTableData.length
}

const reset = async () => {
  inputName.value = ''
  dateTime.value = null
  await getAllList()
  toPageData(1)
}

let currentPage = ref(1)
const toPageData = (page) => {
  currentPage.value = page
  // 根据页数 请求数组的信息
  // 如果有分页 则进行分页 每页20条
  const arr = JSON.parse(JSON.stringify(oriTableData))

  const start = (page - 1) * 10
  const end = (page - 1) * 10 + 10

  showTableData.value = arr.slice(start, end)
}

// 删除提交
const confirmDelete = async () => {
  try {
    const res = await _deleteFile(deleteInfo.value.id)
    if (res?.data?.code == 200) ElMessage.success('删除成功')
    if (res?.data?.code !== 200) ElMessage.error('删除失败')
    showDeleteDialog.value = false
    await getAllList()
    toPageData(currentPage.value)
  } catch (error) {
    console.log(error)
    showDeleteDialog.value = false
    ElMessage.error('删除失败')
  }
}

//
const toDownloadFilePage = () => {
  const url = window.location.href
  const match = url.match(/https?:\/\/([^\/:#]+)/)
  window.open(`${match[0]}:8899`, '_blank')
}

// 取消
const cancel = () => {
  showDeleteDialog.value = false
}

// 格式化文件大小
const formatSize = (row, column, cellValue) => {
  if (cellValue < 1024 * 1024) {
    return (cellValue / 1024).toFixed(2) + ' KB' // 小于 1 MB
  }

  if (cellValue < 1024 * 1024 * 1024) {
    return (cellValue / (1024 * 1024)).toFixed(2) + ' MB' // 小于 1 GB
  }

  return (cellValue / (1024 * 1024 * 1024)).toFixed(2) + ' GB' // 大于等于 1 GB
}

onMounted(async () => {
  await getAllList()
  toPageData(1)
})
</script>

<template>
  <div class="list-container">
    <div class="title">文件传输列表</div>

    <div class="top">
      <!-- 输入和日期 -->
      <div class="inputAndPicker">
        <div class="showInputEle">
          <p>文件名称：</p>
          <el-input @keydown.enter="searchByNameDate" v-model="inputName" style="width: 200px" placeholder="请输入名字" />
        </div>
        <div class="showInputEle date">
          <p>传输时间：</p>
          <el-config-provider :locale="zhCn">
            <el-date-picker @keydown.enter="searchByNameDate" v-model="dateTime" type="datetimerange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" />
          </el-config-provider>
        </div>
        <!-- 按钮查询 -->
        <div class="btns">
          <div class="btn_bd" @click="searchByNameDate">查询</div>
          <div class="btn_bg" @click="reset">重置</div>
        </div>
      </div>

      <!-- 按钮查询 -->
      <div class="btns">
        <div class="btn_bg" @click="toDownloadFilePage">导出配置文件</div>
        <!-- <div class="btn_bg" @click="downloadFile2">导出日志</div> -->
        <div class="btn_bg" style="width: 100px" @click="store.fileTransferTitle = 2">传输新文件</div>
      </div>
    </div>

    <div class="showTable showTableEle3">
      <el-table :data="showTableData" border style="width: 100%" show-overflow-tooltip>
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column prop="file-name" label="文件名称" />
        <el-table-column prop="file-size" label="文件大小" align="center" :formatter="formatSize" width="120" />
        <el-table-column prop="folder" label="传输地址" />
        <el-table-column prop="last-modified" label="传输时间" width="180" />
        <el-table-column label="操作" width="80" align="center">
          <template #default="{ row }">
            <el-button type="danger" :icon="Delete" @click="openDiglog(row)" />
          </template>
        </el-table-column>
      </el-table>

      <div class="page showPageEle">
        <el-pagination background layout="prev, pager, next" :default-page-size="10" :total="total" @current-change="toPageData" />
      </div>
    </div>

    <!-- 删除的弹出确认框 -->
    <confirmDialog v-if="showDeleteDialog" :msg="deleteInfo" :confirm="confirmDelete" :cancel="cancel" />
  </div>
</template>

<style lang="less" scoped>
.list-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  font-size: 14px !important;

  .title {
    font-size: 14px;
    font-weight: 700;
    height: 36px;
    line-height: 36px;
    margin-top: 12px;
  }

  .top {
    height: 48px;
    width: 100%;
    display: flex;
    align-items: center;
    margin-top: 12px;
    .inputAndPicker {
      height: 100%;
      flex: 1;
      display: flex;
      align-items: center;
      > div {
        height: 30px;
        display: flex;
        align-items: center;
        font-size: 14px;
        margin-right: 60px;
      }
    }

    .btns {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      > div {
        height: 24px;
        border-radius: 4px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        line-height: 24px;
        margin-right: 0px;
        margin-left: 20px;
        padding: 2px 6px;
      }
    }
  }

  .showInputEle {
    > p {
      height: 26px;
      line-height: 24px;
    }
  }
  .top-title {
    height: 30px;
    width: 100%;
    display: flex;
    align-items: center;
    > div {
      height: 26px;
      display: flex;
      align-items: center;
      color: black;
      cursor: pointer;
      border-radius: 4px;
      font-size: 14px;
      > p {
        height: 26px;
        line-height: 26px;
      }
    }
    > div:nth-child(2) {
      height: 26px;
      width: auto;
      padding: 0 6px 0 6px;
      margin-left: 54px;
    }

    .down:nth-child(3) {
      margin-left: 32px;
    }
  }

  .showTable {
    flex: 1;
    margin-top: 20px;
    .page {
      display: flex;
      justify-content: flex-end;
      margin-right: 0;
      margin-top: 20px;
    }
    .el-button {
      height: 22px;
      width: 18px;
      border-radius: 2px;
      padding: 0;
    }
  }
}
</style>
